package com.dragon.user_service.Controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.user_service.Exception.BusinessException;
import com.dragon.user_service.Exception.StateCode;
import com.dragon.user_service.annotation.AuthCheck;
import com.dragon.user_service.common.BaseResponse;
import com.dragon.user_service.common.DeleteRequest;
import com.dragon.user_service.constant.UserConstant;
import com.dragon.user_service.domain.dto.request.user.*;
import com.dragon.user_service.domain.entity.User;
import com.dragon.user_service.domain.vo.user.LoginUserVO;
import com.dragon.user_service.domain.vo.user.UserVO;
import com.dragon.user_service.service.UserService;
import com.dragon.user_service.util.AuthCheckUtil;
import com.dragon.user_service.util.ResultUtils;
import com.dragon.user_service.util.ThrowUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


@RestController
@RequestMapping(path = "/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private AuthCheckUtil authCheckUtil;

    @GetMapping("/health")
    public BaseResponse<String> hello() {
        System.out.println(ResultUtils.success("已经成功返回!"));
        return ResultUtils.success("已经成功返回!");
    }

    //用户注册
    @PostMapping("/register")
    public BaseResponse<Boolean> Register(@RequestBody UserRegisterRequest userRegisterRequest, HttpServletRequest request){
        boolean state = userService.userRegister(userRegisterRequest, request);
        return ResultUtils.success(state, StateCode.SUCCESS,"注册成功");
    }

    //登陆生成JWT TOKEN
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> Login(@RequestBody UserLoginRequest userLoginRequest, HttpServletResponse response){
        LoginUserVO loginUserVO = userService.userLogin(userLoginRequest,response);
        return ResultUtils.success(loginUserVO, StateCode.SUCCESS,"登陆成功");
    }



    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest 查询请求参数
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest,HttpServletRequest request) {
        ThrowUtil.throwIf(userQueryRequest == null, StateCode.PARAMS_ERROR);
//        User loginUser = userService.getLoginUser(request);

        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        //进行过滤
        List<UserVO> userVOFilterList = authCheckUtil.filterList(request, userVOList);
        userVOPage.setRecords(userVOFilterList);
        return ResultUtils.success(userVOPage);
    }
    /**
     * 根据 id 获取用户（仅超级管理员）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.SUPER_ADMIN_ROLE)
    public BaseResponse<User> getUserById(Long id,HttpServletRequest request) {
        authCheckUtil.checkAuth(request,id);
        User user = userService.getUserById(id);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(Long userId,HttpServletRequest request) {
        authCheckUtil.checkAuth(request,userId);
        UserVO userVOById = userService.getUserVOById(userId);
        return ResultUtils.success(userVOById);
    }

    /**
     * 更新用户-修改用户信息
     */
    @PostMapping("/update")

    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getUser_id() == null) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        authCheckUtil.checkAuth(request,userUpdateRequest.getUser_id());
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }



    @PostMapping("/resetPassword")
    public BaseResponse<Boolean> updatePassword(@RequestBody userUpdatePasswordRequest updatePasswordRequest,HttpServletRequest request) {
        if (updatePasswordRequest == null || updatePasswordRequest.getUser_id() == null) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        authCheckUtil.checkAuth(request, updatePasswordRequest.getUser_id());
        User user = new User();
        //如果密码长度小于8位，报错
        String resetPassword = updatePasswordRequest.getResetPassword();
        ThrowUtil.throwIf(resetPassword.length()<8,StateCode.PARAMS_ERROR,"密码长度不能小于8位");
        String encryptResetPassword = userService.getEncryptPassword(resetPassword);

        user.setUserPassword(encryptResetPassword);
        user.setUser_id(updatePasswordRequest.getUser_id());

        boolean result = userService.updateById(user);
        ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


// <----------------------------------------------------------------------

    @GetMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request){
        boolean state = userService.userLogout(request);
        return ResultUtils.success(state,StateCode.SUCCESS,"退出账号成功");
    }
    /**
     * 创建用户
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtil.throwIf(userAddRequest == null, StateCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 默认密码 12345678
        final String DEFAULT_PASSWORD = "12345678";
        String encryptPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        user.setUserRole(UserConstant.USER_ROLE);
        boolean result = userService.save(user);
        ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
        return ResultUtils.success(user.getUser_id());
    }


    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUserVO(HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        LoginUserVO loginUserVO = userService.getLoginUserVO(loginUser);
        return ResultUtils.success(loginUserVO,StateCode.SUCCESS);
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    @PostMapping("/users")
    public BaseResponse<Page<UserVO>> listUsersVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtil.throwIf(userQueryRequest == null, StateCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }
}
